import json

from django import http
from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from django.views import View

from homes.models import Area, House, Facility, HouseImage

#获取城区
from libs.qiniuyun.qiniu_storage import storage
from order.models import Order
from settings import QINIU_URL
from users.models import User


class AreasView(View):
    def get(self,request):
        data=[]
        areas=Area.objects.all()
        for area in areas:
            area_dict={
                "aid": area.id,
                "aname": area.name
            }
            data.append(area_dict)
            # print(area.name)
        content={
            "errmsg": "获取成功",
            "errno": "0",
            "data": data
        }

        return http.JsonResponse(content)

#发布房源
class AddHouseView(View):

    def get(self,request):
        aid=request.GET.get('aid')
        start_day=request.GET.get('sd')
        end_day=request.GET.get('ed')
        sort_key=request.GET.get('sk')
        page=request.GET.get('p')
        if sort_key=='booking':
            sk = '-order_count'
        elif sort_key=='price-inc':
            sk='price'
        elif sort_key=='price-des':
            sk = '-price'
        else:
            sk='-id'
        houses=House.objects.filter(area_id=aid).order_by(sk)
        house_list=[]
        for house in houses:
            order_counts=Order.objects.filter(house_id=house.id).filter(~Q(Q(begin_date__gt=end_day)|Q(end_date__lt=start_day))).count()
            if order_counts==0:
                house_dict={
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": (QINIU_URL+str(house.index_image_url)),
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": (QINIU_URL+str(house.user.avatar))
                }
                house_list.append(house_dict)
        content={
            "data": {
                "houses":house_list,
                "total_page": page
            },
            "errmsg": "请求成功",
            "errno": "0"
        }
        return http.JsonResponse(content)



    def post(self,request):
        title = json.loads(request.body.decode()).get("title")
        price = json.loads(request.body.decode()).get("price")
        area_id = json.loads(request.body.decode()).get("area_id")
        address = json.loads(request.body.decode()).get("address")
        room_count = json.loads(request.body.decode()).get("room_count")
        acreage = json.loads(request.body.decode()).get("acreage")
        unit = json.loads(request.body.decode()).get("unit")
        capacity = json.loads(request.body.decode()).get("capacity")
        beds = json.loads(request.body.decode()).get("beds")
        deposit = json.loads(request.body.decode()).get("deposit")
        min_days = json.loads(request.body.decode()).get("min_days")
        max_days = json.loads(request.body.decode()).get("max_days")
        facility_list = json.loads(request.body.decode()).get("facility")
        # area_id = json.loads(request.body.decode()).get("area_id")
        username = request.session.get('username')
        try:
            user = User.objects.get(mobile=username)
            area = Area.objects.get(id=area_id)
            house=House.objects.create(
                user=user,
                area=area,
                title=title,
                price = price,
                address = address,
                room_count = room_count,
                acreage = acreage,
                unit = unit,
                capacity = capacity,
                beds = beds,
                deposit = deposit,
                min_days = min_days,
                max_days = max_days,
            )
            # house=House()
            #     title=title,
            #     price = price,
            #     address = address,
            #     room_count = room_count,
            #     acreage = acreage,
            #     unit = unit,
            #     capacity = capacity,
            #     beds = beds,
            #     deposit = deposit,
            #     min_days = min_days,
            #     max_days = max_days,
            # )
            # print(house.id)
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "新增失败1"})

        facilitys=Facility.objects.filter(id__in=facility_list)
        for facility in facilitys:
            house.facility.add(facility)
        try:
            house.save()
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "新增失败2"})

        return http.JsonResponse({"errno": "0", "errmsg": "新增成功","data":{"house_id":house.id}})

#上传房子图片
class AddHouseImageView(View):


    #上传房子u图片
    def post(self,request,house_id):
        content = {}
        file_name = request.FILES.get('house_image')
        # print(type(file_name),file_name)
        # with open(file_name, "rb") as f:
        house_image_url = storage(file_name.read())
        username = request.session.get('username')
        if not username:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})
        try:
            house=House.objects.get(id=house_id)
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "该房子不存在"})
        if not house.index_image_url:
            house.index_image_url=house_image_url
            house.save()
        HouseImage.objects.create(
            house=house,
            url=house_image_url
        )


        house_image_url = QINIU_URL + house_image_url
        content = {
            "data": {
                "url": house_image_url
            },
            "errno": "0",
            "errmsg": "图片上传成功"
        }

        return http.JsonResponse(content)


#房屋首页推荐
class HouseIndexView(View):
    def get(self,request):
        house_list=[]
        houses=House.objects.all().order_by('-order_count')[0:5]
        for house in houses:
            house_dict={
                "house_id": house.id,
                "img_url": (QINIU_URL+house.index_image_url),
                "title": house.title
            }
            house_list.append(house_dict)


        content={
            "data": house_list,
            "errmsg": "OK",
            "errno": "0"
        }
        return http.JsonResponse(content)


#房屋详细信息
class HouseDetailView(View):
    def get(self,request,house_id):
        username = request.session.get('username')
        if not username:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})
        try:
            user = User.objects.get(mobile=username)
        except:
            return http.JsonResponse({"errno": "4101", "errmsg": "未登录"})
        try:
            house = House.objects.get(id=house_id)
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "该房子不存在"})
        try:
            imgs = HouseImage.objects.filter(house_id=house_id)
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "该房子不存在"})
        try:
            orders =Order.objects.filter(house_id=house_id)
        except:
            return http.JsonResponse({"errno": "400", "errmsg": "该房子不存在"})
        facility_list=[]
        for facility in house.facility.all():
            facility_list.append(facility.id)
        img_list=[]
        for img in imgs:
            img_url=(QINIU_URL+img.url)
            img_list.append(img_url)
        comments_list=[]
        for order in orders:
            comment_dict={
                "comment": order.comment,
                "ctime": order.create_time,
                "user_name": order.user.username
            }
            comments_list.append(comment_dict)

        content={
            "data": {
                "house": {
                    "acreage": house.acreage,
                    "address": house.address,
                    "beds": house.beds,
                    "capacity": house.capacity,
                    "comments": comments_list,
                    "deposit": house.deposit,
                    "facilities":facility_list,
                    "hid": house.id,
                    "img_urls":img_list,
                    "max_days": house.max_days,
                    "min_days": house.min_days,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "unit": house.unit,
                    "user_avatar": (QINIU_URL+str(house.user.avatar)),
                    "user_id": house.user.id,
                    "user_name": house.user.username
                },
                "user_id": user.id
            },
            "errmsg": "OK",
            "errno": "0"
        }
        return http.JsonResponse(content)
